<?php

/**
* @version $Id: mod_sobi2customfields.php 5203 2010-12-03 02:45:14Z  $
* @package Joomla 1.5
* @copyright Copyright (C) 2010 Miguel Puig. All rights reserved.
* @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
* This is a module to display A Custom fields module for Sobi2
*/

defined('_JEXEC') or die('Direct Access to this location is not allowed.');

class ModSobicustomfields
{

    private function getFields_data($fieldsids,$item_id)
    {
    	$db = &JFactory::getDBO();
		$query  = "SELECT a.fieldid as field_id,c.langValue as field_name, b.data_txt as value, a.fieldType as type";
		$query .= " FROM #__sobi2_fields as a";
		$query .= " INNER JOIN #__sobi2_fields_data as b ON a.fieldid=b.fieldid";
		$query .= " INNER JOIN #__sobi2_language as c ON a.fieldid=c.fieldid";
		$query .= " WHERE a.enabled = 1";
		$query .= " AND c.sobi2Section='fields'";
		$query .= " AND b.itemid={$item_id}";
		$query .= " AND a.fieldid IN (";
			if(is_array($fieldsids)):
				
				foreach ($fieldsids as $k => $field_id)
				{
					if ($k > 0) $query .= ' , ';
					$query .= $field_id;
				}
			else:
					$query .= $fieldsids;
			endif;		
			
		$query .= ")";
		$query .= " ORDER BY b.data_txt";
    	

    	
		$db->setQuery( $query );
		$fields = $db->loadAssocList();

  		//Check if the value is a select/combo...
  	
  		$i=0;
  		foreach($fields as $field):
  			if(($field['type']==5) OR ($field['type']==6)):
  				
  				$id = $field['fieldid'];
  				$key = $field['value'];

  				$query2  = "SELECT langValue";
  				$query2 .= " FROM #__sobi2_language";
  				$query2 .= " WHERE langKey = '{$key}'";
  				
  				$db->setQuery($query2);
				$result = $db->loadResult();
  
  				$fields[$i]['value'] = $result;
  			endif;
  		$i++;
  		endforeach;


    	return $fields;
    
    }
    
    private function get_last_gallery_item($item_id)
    {
    
    	$db = &JFactory::getDBO();
    	$query = "SELECT imgid, filename, thumb, title,itemid FROM `#__sobi2_plugin_gallery` WHERE itemid = '$item_id' ";
    	$db->setQuery( $query );
		$result = $db->loadAssocList();

		return $result;
    
    }
    
    public function getItems($limit,$now,$catId,$config,$fieldsids)
    {

        $db = &JFactory::getDBO();
 
		$query = "SELECT `title`, `itemid`, `icon`, `image` FROM `#__sobi2_item` 
		WHERE (itemid IN (SELECT itemid FROM #__sobi2_cat_items_relations WHERE catid IN ({$catId}))) AND `published` = 1 AND (`publish_down` > '{$now}' OR `publish_down` = '{$config->nullDate}') 
		ORDER BY `publish_up` DESC LIMIT {$limit}";

		$db->setQuery( $query );
		$s_results = $db->loadObjectList();
		
		
		$i = 0;
		foreach ($s_results as $s_result):
			$item_id = $s_result->itemid;
			$gallery = ModSobicustomfields::get_last_gallery_item($item_id);

				$s_results[$i]->gallery = $gallery;

			$fields = ModSobicustomfields::getFields_data($fieldsids,$item_id);
			$s_results[$i]->fields = $fields;
		$i++;	
		endforeach;

        return $s_results;
    } 
 
 
 	
} 
?>
